package com.practice.communication.block;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Server {
	
	private static final int SERVER_DEFAULT_PORT = 8080;
	
	private static ServerSocket server = null;
	
	private static Executor serverThreadPool = Executors.newFixedThreadPool(4);
	
	public static void start() {
		start(SERVER_DEFAULT_PORT);
	}
	
	public synchronized static void start (int port) {
		if (server != null) return;
		
		try {
			server = new ServerSocket(port);
			
			while(true) {
				Socket socket = server.accept();
				serverThreadPool.execute(new ServerHandler(socket));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (server != null) {
				try {
					server.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			server = null;
		}
	}

}
